#include "event_impl.h"

/////////////////////////////////////////////////////////////////////////////////////////
// 
namespace xos
{
    event_impl::event_impl()
    {
        m_bManulReset = false;
        m_hEvent = 0;
    }

    event_impl::~event_impl()
    {
        term();
    }

    ////////////////////////////////////////////////////////////////////////////////////
    // 

    int event_impl::init()
    {
        int nRet = 0;

        if( !m_hEvent )
        {
            m_hEvent = CreateEvent( 0, FALSE, FALSE, 0 );
            m_bManulReset = false;
        }

        ResetEvent( m_hEvent );

        return nRet;
    }

    int event_impl::term()
    {
        int nRet = 0;

        if( m_hEvent )
        {
            CloseHandle( m_hEvent );
            m_hEvent = 0;
        }

        m_bManulReset = false;

        return nRet;
    }

    ////////////////////////////////////////////////////////////////////////////////////
    // 

    unsigned long event_impl::wait( unsigned long ulMilliseconds )
    {
        unsigned long ulRet = EVENT_WAIT_FAILED;
        int nRet = 0;

        int dwRet = WaitForSingleObject( m_hEvent, ulMilliseconds );

        switch( dwRet )
        {
        case WAIT_TIMEOUT:
            {
                ulRet = EVENT_WAIT_TIMEOUT;
            }
            break;
        case WAIT_OBJECT_0:
            {
                ulRet = EVENT_WAIT_OBJECT_0;
            }
            break;
        }

        return ulRet;
    }

    int event_impl::set_event_type( bool bManulReset )
    {
        int nRet = 0;

        if( m_bManulReset != bManulReset )
        {
            m_bManulReset = bManulReset;
            CloseHandle( m_hEvent );
            m_hEvent = CreateEvent( 0, bManulReset, FALSE, 0 );
        }

        return nRet;
    }

    int event_impl::reset_event()
    {
        int nRet = 0;
        ResetEvent( m_hEvent );
        return nRet;
    }

    int event_impl::set_event()
    {
        int nRet = 0;
        SetEvent( m_hEvent );
        return nRet;
    }

    int event_impl::release()
    {
        int nRet = 0;

        term();
        put_back_lock();

        return nRet;
    }
} // xos
